package com.meichis.yndms.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Build;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;

import androidx.databinding.DataBindingUtil;

import com.meichis.mcsappframework.encrypt.AESProvider;
import com.meichis.yndms.R;
import com.meichis.yndms.common.MCode;
import com.meichis.yndms.databinding.ActivityNoticeDetailBinding;
import com.meichis.yndms.hybrid.CallbackContext;
import com.meichis.yndms.hybrid.HybridInterface;
import com.meichis.yndms.hybrid.MCSChromeClient;
import com.meichis.yndms.hybrid.MCSWebViewClient;
import com.meichis.yndms.model.Notice;
import com.meichis.yndms.ui.common.BaseActivity;

public class NoticeDetailActivity extends BaseActivity implements HybridInterface {

    private ActivityNoticeDetailBinding binding;

    private View customView;

    /**
     * 视频全屏参数
     */
    protected static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
    private FrameLayout fullscreenContainer;


    private WebChromeClient.CustomViewCallback customViewCallback;

    @Override
    protected void setDataBindingContentView() {
        binding = DataBindingUtil.setContentView(this, R.layout.activity_notice_detail);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED,
                WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
    }

    @Override
    protected void init() {
        binding.navigation.txtTitle.setText(getIntent().getStringExtra(MCode.TYPE));
        binding.navigation.navBack.setOnClickListener(v -> onBackPressed());

        binding.tvTitle.setText(getIntent().getStringExtra(MCode.TITLE));
        binding.tvDate.setText(getIntent().getStringExtra(MCode.DATE));

        binding.web.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        binding.web.getSettings().setLoadsImagesAutomatically(true);
        binding.web.getSettings().setBuiltInZoomControls(true);
        binding.web.getSettings().setDisplayZoomControls(false);
        binding.web.getSettings().setJavaScriptEnabled(true);
        binding.web.getSettings().setTextZoom(300);
        binding.web.setBackgroundColor(0);


        binding.web.getSettings().setPluginState(WebSettings.PluginState.ON);
        binding.web.getSettings().setUseWideViewPort(true); // 关键点
        binding.web.getSettings().setAllowFileAccess(true); // 允许访问文件
        binding.web.getSettings().setSupportZoom(true); // 支持缩放
        binding.web.getSettings().setLoadWithOverviewMode(true);
        binding.web.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE); // 不加载缓存内容

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            binding.web.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }

        binding.web.setWebChromeClient(new MCSChromeClient(this));
        MCSWebViewClient webViewClient = new MCSWebViewClient();
        binding.web.setWebViewClient(webViewClient);
        binding.web.setDownloadListener((url, userAgent, contentDisposition, mimeType, contentLength) -> {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.addCategory(Intent.CATEGORY_BROWSABLE);
            intent.setData(Uri.parse(url));
            startActivity(intent);
        });
        loadNotice((Notice) getIntent().getSerializableExtra(MCode.NOTICE));
    }


    private void loadNotice(Notice notice) {
        String content = notice.getNoticeDetail().replace("<video", "<video style=\"min-width:100%;max-width:100%;height:auto\" ");

        StringBuilder jsstr = new StringBuilder();
        jsstr.append("<body onload=\"ResizeVideo();\">");
        jsstr.append(content);
        jsstr.append("</body>");
        //  jsstr.append(getJsStr());
        binding.web.setWebChromeClient(new VideoWebChromeClient(this));


        binding.web.loadDataWithBaseURL(null, jsstr.toString(), "text/html", "utf-8", null);
    }

    private class VideoWebChromeClient extends MCSChromeClient {

        public VideoWebChromeClient(HybridInterface hybrid) {
            super(hybrid);
        }

        /*** 视频播放相关的方法 **/

        @Override
        public View getVideoLoadingProgressView() {
            FrameLayout frameLayout = new FrameLayout(NoticeDetailActivity.this);
            frameLayout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            return frameLayout;
        }

        @Override
        public void onShowCustomView(View view, CustomViewCallback callback) {
            showCustomView(view, callback);
        }

        @Override
        public void onHideCustomView() {
            hideCustomView();
        }


    }

    /**
     * 将页面视频，设置为窗口宽度
     *
     * @return
     */
    private String getJsStr() {
        StringBuilder jsstr = new StringBuilder();
        jsstr.append("<script type='text/javascript'>");
        jsstr.append("function ResizeVideo() { ");
        jsstr.append("var video = document.getElementsByTagName(\"video\");");
        jsstr.append("for(i=0;i <video.length;i++){");
        jsstr.append("video[i].style.width = document.body.clientWidth;");
//        jsstr.append("video[i].style.height = document.body.clientHeight/2;");
        jsstr.append("}");

        jsstr.append("}");
        jsstr.append("</script>");
        jsstr.append("<br />");
        return jsstr.toString();
    }


    /**
     * 视频播放全屏
     **/
    private void showCustomView(View view, WebChromeClient.CustomViewCallback callback) {
        // if a view already exists then immediately terminate the new one
        if (customView != null) {
            callback.onCustomViewHidden();
            return;
        }

        NoticeDetailActivity.this.getWindow().getDecorView();

        FrameLayout decor = (FrameLayout) getWindow().getDecorView();
        fullscreenContainer = new FullscreenHolder(NoticeDetailActivity.this);
        fullscreenContainer.addView(view, COVER_SCREEN_PARAMS);
        decor.addView(fullscreenContainer, COVER_SCREEN_PARAMS);
        customView = view;
        setStatusBarVisibility(false);
        customViewCallback = callback;
    }

    /**
     * 隐藏视频全屏
     */
    private void hideCustomView() {
        if (customView == null) {
            return;
        }

        setStatusBarVisibility(true);
        FrameLayout decor = (FrameLayout) getWindow().getDecorView();
        decor.removeView(fullscreenContainer);
        fullscreenContainer = null;
        customView = null;
        customViewCallback.onCustomViewHidden();
        binding.web.setVisibility(View.VISIBLE);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//竖屏
    }

    /**
     * 全屏容器界面
     */
    static class FullscreenHolder extends FrameLayout {

        public FullscreenHolder(Context ctx) {
            super(ctx);
            setBackgroundColor(ctx.getResources().getColor(android.R.color.black));
        }

        @Override
        public boolean onTouchEvent(MotionEvent evt) {
            return true;
        }
    }

    private void setStatusBarVisibility(boolean visible) {
        int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
        getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);// 横屏
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                /** 回退键 事件处理 优先级:视频播放全屏-网页回退-关闭页面 */
                if (customView != null) {
                    hideCustomView();
                } else if (binding.web.canGoBack()) {
                    binding.web.goBack();
                } else {
                    finish();
                }
                return true;
            default:
                return super.onKeyUp(keyCode, event);
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (binding.web != null) {
            binding.web.onResume();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (binding.web != null) {
            binding.web.onPause();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (binding.web != null) {
            binding.web.destroy();
        }
    }

    @Override
    public void execute(int CallType, String ControlID, Object Revalue, String FUNCCallBack) {

    }

    @Override
    public void setActivityResultCallback(CallbackContext callback) {

    }
}
